package net.dubboclub.netty4.help;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.rpc.*;
import com.alibaba.dubbo.rpc.protocol.AbstractInvoker;

/**
 * Created by bieber on 16/3/21.
 * netty4通信层的wrapper,如果依赖了netty4,那么通信层直接走netty4,避免找不到netty的通信层插件
 */
public class Netty4ProtocolWrapper implements Protocol {

    private Protocol protocol;

    public Netty4ProtocolWrapper(Protocol protocol){
        this.protocol = protocol;
    }

    @Override
    public int getDefaultPort() {
        return protocol.getDefaultPort();
    }

    @Override
    public <T> Exporter<T> export(final Invoker<T> invoker) throws RpcException {
        URL url = invoker.getUrl();
        if(Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())){
            return protocol.export(invoker);
        }
        url = url.addParameterIfAbsent(Constants.TRANSPORTER_KEY,"netty4");
        return protocol.export(new AbstractInvoker<T>(invoker.getInterface(),url) {
            @Override
            protected Result doInvoke(Invocation invocation) throws Throwable {
                return invoker.invoke(invocation);
            }
        });
    }

    @Override
    public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
        if(Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())){
            return protocol.refer(type,url);
        }
        url = url.addParameterIfAbsent(Constants.CLIENT_KEY,"netty4");
        return protocol.refer(type,url);
    }

    @Override
    public void destroy() {
        protocol.destroy();
    }
}
